<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目分值" prop="score">
        <el-input v-model="queryParams.score" placeholder="请输入题目分值" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="题干信息" prop="content">
        <el-input v-model="queryParams.contentString" placeholder="题干信息" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建人id" prop="createdBy">
        <el-input v-model="queryParams.createdBy" placeholder="请输入创建人id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="题目类型" prop="questionType">
        <el-select v-model="queryParams.questionType" clearable placeholder="请选择问题类型">
          <el-option label="单选" value="1"></el-option>
          <el-option label="多选" value="2"></el-option>
          <el-option label="判断" value="3"></el-option>
          <el-option label="填空" value="4"></el-option>
          <el-option label="简答" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['question:question:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['question:question:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['question:question:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['question:question:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目id" align="center" prop="id" />
      <el-table-column label="类型" align="center" prop="questionType">
        <template slot-scope="scope">
          <span v-if="scope.row.questionType == '1'">单选</span>
          <span v-if="scope.row.questionType == '2'">多选</span>
          <span v-if="scope.row.questionType == '3'">判断</span>
          <span v-if="scope.row.questionType == '4'">填空</span>
          <span v-if="scope.row.questionType == '5'">简答</span>
        </template>
      </el-table-column>
      <el-table-column label="题目分值" align="center" prop="score" />
      <el-table-column label="正确答案" align="center" prop="correctArrays" />
      <el-table-column label="关联题干信息内容ID" align="center" prop="contentId" />
      <el-table-column label="题干信息" align="center" prop="contentString" />
      <el-table-column label="创建人ID" align="center" prop="createdBy" />
      <el-table-column label="状态1正常,0禁用" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['question:question:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['question:question:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改题库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
        <el-form-item label="问题类型">
          <el-select v-model="dynamicValidateForm.questionType" placeholder="请选择问题类型">
            <el-option label="单选" value="1"></el-option>
            <el-option label="多选" value="2"></el-option>
            <el-option label="判断" value="3"></el-option>
            <el-option label="填空" value="4"></el-option>
            <el-option label="简答" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="答案">
          <!-- 单选 -->
          <el-radio-group v-if="dynamicValidateForm.questionType == 1" v-model="dynamicValidateForm.correctArrays[0]">
            <el-radio v-for="(opt, index) in dynamicValidateForm.content" v-if="opt.key != 'title'" :label="opt.key"
              :value="opt.key">
            </el-radio>
          </el-radio-group>
          <!-- 多选 -->
          <el-checkbox-group v-if="dynamicValidateForm.questionType == 2" v-model="dynamicValidateForm.correctArrays">
            <el-checkbox v-for="(opt, index) in dynamicValidateForm.content" v-if="opt.key != 'title'" :label="opt.key"
              :value="opt.key">
            </el-checkbox>
          </el-checkbox-group>
          <!-- 判断 -->
          <el-radio-group v-if="dynamicValidateForm.questionType == 3" v-model="dynamicValidateForm.correctArrays[0]">
            <el-radio v-for="(opt, index) in dynamicValidateForm.content" v-if="opt.key != 'title'" :label="opt.key"
              :value="opt.key">
            </el-radio>
          </el-radio-group>
          <!-- 填空 -->
          <el-input v-if="dynamicValidateForm.questionType == 4 || dynamicValidateForm.questionType == 5"
            type="textarea" v-model="dynamicValidateForm.correctArrays[0]" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item prop="score" label="分数">
          <el-input v-model="dynamicValidateForm.score"></el-input>
        </el-form-item>
        <el-form-item v-for="(opt, index) in dynamicValidateForm.content" :label="opt.key" :key="opt.key"
          :prop="'content.' + index + '.value'" :rules="{
            required: true, message: '选项不能为空', trigger: 'blur'
          }">
          <el-input v-model="opt.value"></el-input>
          <el-button v-if="opt.key != 'title' && showAddOption()" @click.prevent="removeOption(opt)">删除选项</el-button>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="showAddOption()" @click="addOption">新增选项</el-button>
        <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
        <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/question/question";

export default {
  name: "Question",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionType: null,
        score: null,
        contentString: null,
        createdBy: null,
        status: null,
        deleteFlag: null
      },
      // 表单参数
      form: {},
      // 动态表单
      dynamicValidateForm: {
        questionType: null,
        score: null,
        correctArrays: [],
        content: [{
          key: 'title',
          value: ''
        }]
      },
      // 表单校验
      rules: {
        questionType: [
          { required: true, message: "类型1.单选 2.多选 3.判断 4.填空 5.简答不能为空", trigger: "change" }
        ],
        score: [
          { required: true, message: "题目分值不能为空", trigger: "blur" }
        ],
        correct: [
          { required: true, message: "正确答案不能为空", trigger: "blur" }
        ],
        contentId: [
          { required: true, message: "题目 填空、 题干、解析、答案等信息的id不能为空", trigger: "blur" }
        ],
        createdBy: [
          { required: true, message: "创建人id不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态1正常,0禁用不能为空", trigger: "blur" }
        ],
        deleteFlag: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询题库列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.dynamicValidateForm = {
        questionType: null,
        score: null,
        correctArrays: [],
        content: [{
          key: 'title',
          value: ''
        }]
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQuestion(id).then(response => {
        this.dynamicValidateForm = response.data;
        this.dynamicValidateForm.correctArrays = response.data.correctArrays;
        this.open = true;
        this.title = "修改题库";
      });
    },
    resetForm(formName) {
      this.reset()
    },
    removeOption(item) {
      var index = this.dynamicValidateForm.content.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.content.splice(index, 1)
      }
    },
    addOption() {
      this.dynamicValidateForm.content.push({
        value: '',
        key: String.fromCharCode((this.dynamicValidateForm.content.length - 1) + 65)
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dynamicValidateForm.id != null) {
            updateQuestion(this.dynamicValidateForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.dynamicValidateForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题库编号为"' + ids + '"的数据项？').then(function () {
        return delQuestion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('question/question/export', {
        ...this.queryParams
      }, `question_${new Date().getTime()}.xlsx`)
    },
    showAddOption() {
      let type = this.dynamicValidateForm.questionType;
      if (type == 1 || type == 2 || type == 4) {
        return true;
      }
      return false;
    }
  },
  watch: {
    'dynamicValidateForm.questionType': {
      handler(newVal, oldVal) {
        let form = this.dynamicValidateForm
        if (newVal == 3) {
          form.content = [{ key: 'title', value: '' }, { key: 'A', value: 'T' }, { key: 'B', value: 'F' }];
        } else if (newVal == 5) {
          form.content = [{ key: 'title', value: '' }];
        }
      },
    }
  }
};
</script>
